package com.wkh.datastructure.BinaryTree;

import java.util.LinkedList;
import java.util.Queue;

//求最小深度
public class MinimumDepth {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1,
                new TreeNode(2,null,null),
                new TreeNode(3,
                        null,
                        new TreeNode(4,null,null)));
//        TreeNode root = new TreeNode(1,null,null);
        int count = minDepth2(root);
        System.out.println(count);
    }
    public static int minDepth(TreeNode node){
        if (node == null){
            return 0;
        }
        int d1 = minDepth(node.left);
        int d2 = minDepth(node.right);
        if (d1 == 0){//只有右子树
            return d2+1;//返回右子树的深度+1
        }
        if (d2 == 0){//只有左子树
            return d1+1;//返回左子树的深度+1
        }
        return Integer.min(d1,d2)+1;
    }

    /**
     * 利用层序遍历寻找最小深度
     * @param node
     * @return
     */
    public static int minDepth2(TreeNode node){
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(node);
        int depth = 0;
        while (!queue.isEmpty()){
            int size = queue.size();
            depth++;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                if (poll.left == null && poll.right == null){
                    return depth;
                }
                if (poll.left != null){
                    queue.offer(poll.left);
                }
                if (poll.right != null){
                    queue.offer(poll.right);
                }
            }
        }
        return depth;
    }
}
